package ui;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;

import net.Answer;
import net.MSGType;
import net.ParaReader;
import net.ParaWriter;
import net.Question;
import net.Queues;
import net.dethi;
import net.docghi;
import net.docghi2;
import net.dstraloi;
import net.loadlientuc;
import net.quanlyclient;
import net.quanlydocviet;
import net.tonghopdocghi;
import net.traloi;

import net.msg;


import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Synchronizer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Group;

import db.Dbhandle;
import db.cauhoicoso;
import db.quanlycauhoi;
import db.taodethi;
import db.xemketquathi;

import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.graphics.Color;
import org.eclipse.wb.swt.SWTResourceManager;

public class Server {
	
   
	protected Shell shell;
	
	public  Queues<msg>Sendqueue=new Queues<msg>();
	public  Queues<msg>CMDqueue=new Queues<msg>();
	private ObjectInputStream in=null;
	private ObjectOutputStream out=null;
    private ServerSocket server;
    private ArrayList<tonghopdocghi> array=new ArrayList<tonghopdocghi>();
    private Label labelsomay;
    private List list;
    private int tam=0;
    private String quyen;
    private Label lblNewLabel_1;
    private String Iptoi;
    private Label labelchay;
    private Combo combo;
    private Button bntguitungclient;
    private Button bntguiallclient; 
    private Button btnconnect;
    private String str;
    private Group group;
    private Label lblNewLabel_3;
    private Label lblNewLabel_4;
    private Label lblNewLabel_5;
    private Group group_1;
    private Label lblNewLabel_7;
    private Button bntsoande;
   
    private  ArrayList<dethi> arraylistbode=new ArrayList<dethi>(); 
    private Combo combomakythi;
    private Combo combothang;
    private Combo combonam;
    private Label lblNewLabel_6;
    private Label lblNewLabel_8;
    private Button bntrefesh;
    private int t=0;
    MessageBox ms;
    private Label lblNewLabel_9;
    private Text txtthoigian;
    
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Server window = new Server();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			
			if (!display.readAndDispatch()) {
				//display.sleep();
				
				
			}
			
			//load thong tin may client len list
			
			
			if(t==0)
			{
				loadataYearcombonam();
				t=1;
			}
			
			
			if(!CMDqueue.isEmpty())
			{
				msg dulieu=(msg)CMDqueue.dequeue();
				if(dulieu.getType().equals(new MSGType().getDISCONNECTED()))
				{
					String iP=dulieu.getIP();
					Answer tra=new Answer("", "", "");
					msg hopthutralai=new msg("", iP, tra, "");
					Sendqueue.enqueue(hopthutralai);
					System.out.println("co may ngat ket noi");
					int t;
					for(t=0;t<array.size();t++)
					{
						
						try {
							str = array.get(t).getSocket().getInetAddress().getLocalHost().getHostAddress();
						} catch (UnknownHostException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if(str.equals(dulieu.getIP()))
						{
							array.remove(t);
						}
						
					}
					msg closeCMD = new msg(new MSGType().getCLIENT_UI_CLOSE(), "", "","");
					
					Sendqueue.enqueue(closeCMD); 
					
					
				}
				else{
					if(dulieu.getType().equals(new MSGType().getSEND_NAME()))
					{
						
						System.out.println("gettype:"+dulieu.getType());
						
						
						String[] str1=dulieu.getStr().split("[|]");
						String str="INSERT INTO user VALUES("+"null"+","+"'"+dulieu.getIP()+"'"+","+"'"+str1[0]+"'"+","+"'"+str1[1]+"'"+","+"'"+str1[2]+"'"+")";
						
						new Dbhandle().executeUpdate(str);
					}
					else if(dulieu.getType().equals(new MSGType().getSENT_DATA()))
					{
						ms=new MessageBox(shell);
						ms.setMessage("chung toi da nhan duoc");
						ms.open();
						dstraloi antl=(dstraloi)dulieu.getData();
						int solan=antl.Size()-1;
						while(solan>=0)
						{   traloi tl=antl.get(solan);
							String sqlinsert="INSERT INTO ketqua VALUES("+"null"+","+"'"+dulieu.getIP()+"'"+","+"'"+antl.getMakythi()+"'"+","+"'"+tl.getMACAUHOI()+"'"+","+"'"+tl.getCHON()+"'"+");";
							new Dbhandle().executeUpdate(sqlinsert);
							solan--;
							
							
							
						}
						
						
						String tongsocau="";
						String tongsocaudung="";
						String tongsocausql="select count(IP) from ketqua where IP="+"'"+dulieu.getIP()+"'"+"";
						String socaudungsql="select count(IP) from ketqua inner join cauhoi on " +
								"ketqua.MACAUHOI=cauhoi.MACAUHOI where IP="+"'"+dulieu.getIP()+"'"+" AND dapan=dung";
						try {
							ResultSet rs=new Dbhandle().executeQuery(tongsocausql);
							while(rs.next())
							{
								tongsocau=rs.getString(1);
							
								
							}
							ResultSet rs1=new Dbhandle().executeQuery(socaudungsql);
							while(rs1.next())
							{
							tongsocaudung=rs1.getString(1);	
							
							}
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						Answer an=new Answer(tongsocau, tongsocaudung,"");
						msg guitongsocau=new msg(new MSGType().getCOMPLETED(), dulieu.getIP(), an, "");
						Sendqueue.enqueue(guitongsocau);
						
						
					}
					else if(dulieu.getType().equals(new MSGType().getCOMPLETED()))
					{
						Answer an=new Answer("", "","");
						String tongsocau="";
						String tongsocaudung="";
						String tongsocausql="select count(IP) from ketqua where IP="+"'"+dulieu.getIP()+"'"+"";
						String socaudungsql="select count(IP) from ketqua inner join cauhoi on" 
+"ketqua.MACAUHOI=cauhoi.MACAUHOI where IP="+"'"+dulieu.getIP()+"'"+" AND dapan=dung";
						try {
							ResultSet rs=new Dbhandle().executeQuery(tongsocausql);
							while(rs.next())
							{
								tongsocau=rs.getString(1);
								
							}
							ResultSet rs1=new Dbhandle().executeQuery(socaudungsql);
							while(rs1.next())
							{
							tongsocaudung=rs1.getString(1);	
								
							}
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
					}
				
				}
			//	Answer an=(Answer)dulieu.getData();
				//String string="IP is:"+dulieu.getIP()+"str is: "+dulieu.getStr()+"tra loi: "+an.getDapAn();
				
				
			}
			else
			{
				try {
					Thread.sleep(5);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			
			if(tam!=array.size())
			{
				tam=array.size();
				list.removeAll();
				int i;
				for(i=0;i<array.size();i++)
				{
					
					try {
						str = i+".. dia chi ip la: "+array.get(i).getSocket().getInetAddress().getLocalHost().getHostAddress();
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					list.add(str);
					
				}
				
				
			}
			
			labelsomay.setText(Integer.toString(array.size()));

		
				
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(803, 458);
		
		 btnconnect = new Button(shell, SWT.NONE);
		btnconnect.addSelectionListener(new SelectionAdapter() {
		
			@Override
			public void widgetSelected(SelectionEvent e) {
				
				try {
					 server=new ServerSocket(7979);
					 quanlyclient quanly=new quanlyclient(server, CMDqueue, Sendqueue,array);
						quanly.start();
					labelchay.setText("running...");
					btnconnect.setVisible(false);
					
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		}
		);
		btnconnect.setBounds(702, 385, 75, 25);
		btnconnect.setText("Run");
		
		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setBounds(127, 86, 107, 15);
		lblNewLabel.setText("số máy kết nói tới");
		
		 labelsomay = new Label(shell, SWT.NONE);
		labelsomay.setBounds(240, 86, 55, 15);
		
		 list = new List(shell, SWT.BORDER);
		 list.addMouseListener(new MouseAdapter() {
		 	@Override
		 	public void mouseUp(MouseEvent e) {
		 		int ta=list.getSelectionIndex();
		 		if(ta!=-1)
		 		{
		 			
		 			try {
						Iptoi=array.get(ta).getSocket().getInetAddress().getLocalHost().getHostAddress();
					} catch (UnknownHostException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		 		}
		 		
		 		
		 		
		 	}
		 });
		
		list.setBounds(20, 107, 435, 303);
		
		lblNewLabel_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1.setBounds(20, 86, 101, 15);
		lblNewLabel_1.setText("danh sách client ");
		
		labelchay = new Label(shell, SWT.NONE);
		labelchay.setBounds(722, 10, 55, 15);
		
		group = new Group(shell, SWT.NONE);
		group.setBounds(492, -2, 224, 90);
		
		lblNewLabel_3 = new Label(group, SWT.CENTER);
		lblNewLabel_3.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
		lblNewLabel_3.addMouseTrackListener(new MouseTrackAdapter() {
			@Override
			public void mouseHover(MouseEvent e) {
				lblNewLabel_3 .setBackground(SWTResourceManager.getColor(SWT.COLOR_MAGENTA));
			}
			@Override
			public void mouseExit(MouseEvent e) {
				lblNewLabel_3 .setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
			}
		});
		lblNewLabel_3.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				quanlycauhoi qlch=new quanlycauhoi();
				qlch.open();
			}
		});
		lblNewLabel_3.setBounds(10, 10, 130, 21);
		lblNewLabel_3.setText("DANH SÁCH CÂU HỎI");
		
		lblNewLabel_4 = new Label(group, SWT.NONE);
		lblNewLabel_4.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				xemketquathi kqt=new xemketquathi();
				kqt.open();
			}
		});
		lblNewLabel_4.addMouseTrackListener(new MouseTrackAdapter() {
			@Override
			public void mouseHover(MouseEvent e) {
				lblNewLabel_4.setBackground(SWTResourceManager.getColor(SWT.COLOR_MAGENTA));
			}
			@Override
			public void mouseExit(MouseEvent e) {
				lblNewLabel_4 .setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
			}
		});
		lblNewLabel_4.setBounds(10, 37, 119, 15);
		lblNewLabel_4.setText("XEM KẾT QUẢ THI");
		
		lblNewLabel_5 = new Label(group, SWT.NONE);
		lblNewLabel_5.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				taodethi taode=new taodethi();
				taode.open();
				
			}
		});
		lblNewLabel_5.addMouseTrackListener(new MouseTrackAdapter() {
			@Override
			public void mouseHover(MouseEvent e) {
				lblNewLabel_5.setBackground(SWTResourceManager.getColor(SWT.COLOR_MAGENTA));
			}
			@Override
			public void mouseExit(MouseEvent e) {
				lblNewLabel_5 .setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
			}
		});
		lblNewLabel_5.setBounds(10, 58, 98, 22);
		lblNewLabel_5.setText("TẠO ĐỀ THI");
		
		Button bntexit = new Button(shell, SWT.NONE);
		bntexit.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				System.exit(0);
			}
		});
		bntexit.setBounds(722, 37, 55, 35);
		bntexit.setText("Exit");
		
		group_1 = new Group(shell, SWT.NONE);
		group_1.setBounds(10, -2, 476, 82);
		
		 bntguiallclient = new Button(group_1, SWT.NONE);
		 bntguiallclient.setBounds(144, 49, 75, 25);
		 bntguiallclient.addSelectionListener(new SelectionAdapter() {
		 	@Override
		 	public void widgetSelected(SelectionEvent e) {
		 		if(arraylistbode.size()!=0)
		 		{
		 			if(!txtthoigian.getText().equals("")||Isnumber(txtthoigian.getText()))
			 		{
			 			int  dsclient=array.size();
				 		if(dsclient!=0)
				 		{
				 			while(dsclient!=0)
					 		{ 
				 				
				 				//try
				 			//	{
				 					 String iP;
									try {
										iP = array.get(dsclient-1).getSocket().getInetAddress().getLocalHost().getHostAddress();
										
										dethi dethi=new dethi(combomakythi.getText());
										dethi=arraylistbode.get((dsclient-1));
										if(arraylistbode.get(0)==null)
										{
											ms.setMessage( "dannh bi  rong");
											ms.open();
											return;
											
										}
										msg guide=new msg(new MSGType().getSENT_DATA(), iP,dethi ,Integer.toString(Integer.parseInt(txtthoigian.getText())*60) );
							 			Sendqueue.enqueue(guide);
							 			while(true)
							 			{
							 				if(Sendqueue.isEmpty())
							 					break;
							 			}
							 			dsclient=dsclient-1;
									} catch (UnknownHostException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}
							 				
				 			//	}catch(Exception e1){}
					 		}
				 			ms=new MessageBox(shell);
				 			ms.setMessage("chúng tôi đã hoàng thành gửi đề!");
				 			ms.open();
				 			
				 		}else
				 		{
				 			MessageBox ms1=new MessageBox(shell);
				 			ms1.setMessage("chúng tôi chưa thấy client nào kết nói tới  \n vui lòng chờ đợi họ kết nói!");
				 			ms1.open();
				 			return;
				 		}
			 		}else
			 		{
			 			ms=new MessageBox(shell);
			 			ms.setMessage("bạn chưa điền thời gian!\n vui lòng hãy điền lại!");
			 			ms.open();
			 			return;
			 		}
		 			
		 		}
		 		else
		 		{

		 			ms=new MessageBox(shell);
		 			ms.setMessage("bạn chưa tạo bộ đề thi");
		 			ms.open();
		 			return;
		 		}
		 		
		 	}
		 });
		 bntguiallclient.setVisible(false);
		 bntguiallclient.setText("allclient");
		 
		  combo = new Combo(group_1, SWT.NONE);
		  combo.setBounds(71, 49, 55, 23);
		  combo.addSelectionListener(new SelectionAdapter() {
		  	@Override
		  	public void widgetSelected(SelectionEvent e) {
		  		
		  		
		  		String str=combo.getItem(combo.getSelectionIndex());
		  		if(str.equals("all"))
		  		{
		  			bntguiallclient.setVisible(true);
		  			bntguitungclient.setVisible(false);
		  		}
		  		else if(str.equals("select"))
		  		{
		  			bntguiallclient.setVisible(false);
		  			bntguitungclient.setVisible(true);
		  			
		  		}
		  		
		  		
		  	}
		  });
		  combo.setItems(new String[] {"all", "select"});
		  
		  Label lblNewLabel_2 = new Label(group_1, SWT.NONE);
		  lblNewLabel_2.setBounds(10, 52, 55, 20);
		  lblNewLabel_2.setText("Kiểu gửi");
		  
		  lblNewLabel_7 = new Label(group_1, SWT.NONE);
		  lblNewLabel_7.setBounds(251, 15, 63, 15);
		  lblNewLabel_7.setText("Mã Kì Thi");
		  
		  bntsoande = new Button(group_1, SWT.NONE);
		  bntsoande.addSelectionListener(new SelectionAdapter() {
		  	@Override
		  	public void widgetSelected(SelectionEvent e) {
		  		if(!combomakythi.getText().equals(""))
		  		{    arraylistbode=new ArrayList<dethi>(); 
		  			String danhsachmade=" select distinct made from dethi where masokythi="+"'"+combomakythi.getText()+"'"+" ";
		  			try {
						ResultSet rs0=new Dbhandle().executeQuery(danhsachmade);
						int i=1;
						while(rs0.next())
						{
							//lay cau hoi
				  			
				  			String laycauhoisql="select * from cauhoi where macauhoi in(select MACAUHOI FROM " +
				  					"DETHI WHERE made="+i+" and masokythi="+"'"+combomakythi.getText()+"'"+")";
				  		    ResultSet rs=new Dbhandle().executeQuery(laycauhoisql);
				  		   dethi arraylistcauhoicoso=new dethi(combomakythi.getText()); 
				  		    while(rs.next())
				  		    {
				  		    	cauhoicoso ch=new cauhoicoso(rs.getString(1), rs.getString(2),rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6),rs.getString(7),rs.getString(8), rs.getString(9),rs.getString(10));
				  		        arraylistcauhoicoso.add(ch);
				  		     
				  		    }
				  		 //end lay  cau hoi
				  		    
							arraylistbode.add(arraylistcauhoicoso);
				  		    i++;
							
						}
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		  			
		  		 //end tao bo de
		  			MessageBox	ms1=new MessageBox(shell);
		  			
		  			dethi danhsach=new dethi(combomakythi.getText());
		  			danhsach=(dethi)arraylistbode.get(1);
		  			ms1.setMessage("chúng tôi đã tạo đề thi song! vui lòng \n bạn thực hiện việc tiếp theo \n bộ đề cho: "+arraylistbode.size()+" máy");
		  			ms1.open();
		  		}else
		  		{
		  		MessageBox	ms1=new MessageBox(shell);
		  			ms1.setMessage("bạn chưa chọn mã ky thi!");
		  			ms1.open();
		  			
		  		}
		  	
		  	//	arraylistcauhoicoso.add("String");	  		
		  		
		  	}
		  });
		  bntsoande.setBounds(342, 49, 63, 25);
		  bntsoande.setText("soạn đề");
		  
		  combomakythi = new Combo(group_1, SWT.NONE);
		  combomakythi.setBounds(315, 12, 75, 23);
		  
		  combothang = new Combo(group_1, SWT.NONE);
		  combothang.addSelectionListener(new SelectionAdapter() {
		  	@Override
		  	public void widgetSelected(SelectionEvent e) {
		  		loadtacombomakythi();
		  	}
		  });
		  combothang.setItems(new String[] {});
		  combothang.setBounds(173, 12, 46, 23);
		  
		  combonam = new Combo(group_1, SWT.NONE);
		  combonam.addSelectionListener(new SelectionAdapter() {
		  	@Override
		  	public void widgetSelected(SelectionEvent e) {
		  		loadatacombomonth();
		  		
		  	}
		  });
		  combonam.setBounds(59, 12, 46, 23);
		  
		  lblNewLabel_6 = new Label(group_1, SWT.NONE);
		  lblNewLabel_6.setBounds(126, 15, 55, 15);
		  lblNewLabel_6.setText("tháng");
		  
		  lblNewLabel_8 = new Label(group_1, SWT.NONE);
		  lblNewLabel_8.setBounds(10, 15, 38, 15);
		  lblNewLabel_8.setText("năm");
		  
		  bntrefesh = new Button(group_1, SWT.NONE);
		  bntrefesh.addSelectionListener(new SelectionAdapter() {
		  	@Override
		  	public void widgetSelected(SelectionEvent e) {
		  		loadataYearcombonam();
		  		loadatacombomonth();
		  		loadtacombomakythi();
		  	}
		  });
		  bntrefesh.setBounds(411, 49, 55, 25);
		  bntrefesh.setText("Refesh");
		  
		  bntguitungclient = new Button(group_1, SWT.NONE);
		  bntguitungclient.setBounds(132, 49, 88, 25);
		  bntguitungclient.setVisible(false);
		  bntguitungclient.addSelectionListener(new SelectionAdapter() {
		  	@Override
		  	public void widgetSelected(SelectionEvent e) {
		  		Question cauhoi=new Question("001", "tất ca mội vật \n điều chịu ảnh hưởng của?", "VL", "de", "trong luc", "khoi luong ", "thế năng", "động năng","A"); 
		  		msg m1=new msg(new MSGType().getSENT_DATA(), Iptoi, cauhoi,"kythiII");
		  		Sendqueue.enqueue(m1);
		  		
		  	}
		  });
		  bntguitungclient.setText("gửi từng lient");
		  
		  lblNewLabel_9 = new Label(group_1, SWT.NONE);
		  lblNewLabel_9.setBounds(225, 54, 55, 15);
		  lblNewLabel_9.setText("thời gian");
		  
		  txtthoigian = new Text(group_1, SWT.BORDER);
		  txtthoigian.setBounds(281, 51, 55, 21);
		
		
		
		

	}
	public  void loadataYearcombonam()
	
	{
		combonam.removeAll();
		String str="select DISTINCT YEAR(NGAYTHI) from kythi";
		try {
			ResultSet rs=new Dbhandle().executeQuery(str);
			while(rs.next())
			{
				combonam.add(rs.getString(1));
				
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	public void loadatacombomonth()
	
	{
		if(!combonam.getText().equals(""))
		{
			combothang.removeAll();
			
			String str="select DISTINCT month(ngaythi) from kythi where year(ngaythi)="+combonam.getText()+"";
			try {
				ResultSet rs=new Dbhandle().executeQuery(str);
				while(rs.next())
				{
					combothang.add(rs.getString(1));
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
	}
	public void loadtacombomakythi()
	{  combomakythi.removeAll();
		
		if(!combothang.getText().equals(""))
		{
			
			String str="select DISTINCT MASOKYTHI from kythi WHERE month(NGAYTHI)="+"'"+combothang.getText()+"'"+"";
			try {
				ResultSet rs=new Dbhandle().executeQuery(str);
				while(rs.next())
				{
					combomakythi.add(rs.getString(1));
					
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	public boolean Isnumber(String str)
	{
		try
		{
			Integer.parseInt(str);
			return true;
		}catch(Exception e)
		{
			return false;
		}
		
	}
}
